//
//  HMOAuthViewController.swift
//  Weibo
//
//  Created by 李学林 on 15/12/7.
//  Copyright © 2015年 tete. All rights reserved.
//

import UIKit
import SVProgressHUD

let WB_APPKEY = "2841097745"
let WB_APP_SECRET = "6df246ea1c553e9f06358c26848bdf33"
let WB_REDIRECT_URI = "http://www.itheima.com"

class HMOAuthViewController: UIViewController, UIWebViewDelegate {

    private var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        webView.delegate = self
        view = webView
        
        title = "新浪微博登陆"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
        
        webView.loadRequest(NSURLRequest(URL: NetworkTools.shareManager.oAuthUrl))
    }
 
    @objc private func dismiss(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFill(){
        print("autoFill")
        // 了解yohtr35601@163.com
        let jsString = "document.getElementById('userId').value='18519330596';document.getElementById('passwd').value='13932029195'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

}


extension NetworkTools {
    
    var oAuthUrl :NSURL{
       
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URI)"
        
        return NSURL(string: urlString)!
    }
    
 }

extension HMOAuthViewController {
    /**
     当加载请求的时候会调用这个方法
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.URL?.absoluteString else{
            return true
        }
        if !url.hasPrefix(WB_REDIRECT_URI){
            return true
        }
        
        if request.URL!.query!.hasPrefix("code=") {
            printLog(request.URL?.query)
            let code = request.URL!.query!.substringFromIndex("code=".endIndex)
            
            HMWBUserInfoViewModel.sharedAccount.getAccessToken(code, complete: { (isSuccess) -> () in
                
                if !isSuccess{
                    printLog("加载失败")
                    SVProgressHUD.showErrorWithStatus("网络异常")
                    return
                }
                printLog("加载成功,个人信息获取成功")
                SVProgressHUD.dismiss()
                
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    NSNotificationCenter.defaultCenter().postNotificationName(HMSwitchRootVCNotifation, object: self)
                })
            })
        } else {
            print(request.URL)
            // 将当前页面,给干掉
            dismiss()
        }
        return false
    }
    // progress视图
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
